package club.janna.concurrency.example.count;

import club.janna.concurrency.annotation.ThreadUnSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 并发测试，线程不安全的
 * @Auther: guopanbo
 * @Date: 2018/7/21 23:41
 * @Description:
 */
@Slf4j
@ThreadUnSafe
public class CountExample1 {

    /**
     * 计数总和
     */
    private static int countTotal = 5000;
    /**
     * 并发线程数
     */
    private static int threadTotal = 200;
    /**
     * 计数器
     */
    private static int count = 0;

    public static void main(String[] args) {
        long s = System.currentTimeMillis();
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(countTotal);
        for(int i = 0; i < countTotal; i ++)
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    log.info("exception:{}", e.getMessage());
                    e.printStackTrace();
                }
                add();
                semaphore.release();
                countDownLatch.countDown();
            });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        log.info("count = {}", count);
        log.info("time = {}", System.currentTimeMillis() - s);
    }

    private static void add() {
        count ++;
    }
}
